package com.gears_software.sxdc.dccx.data.finder.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.widget.Toast;

import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.sharedPreference.DCCXSp_;
import com.gears_software.sxdc.dccx.ui.activity.LoginActivity_;
import com.gears_software.sxdc.dccx.ui.util.NetUtils;
import com.github.mzule.activityrouter.annotation.Router;
import com.j256.ormlite.stmt.query.In;
import com.orhanobut.logger.Logger;
import com.sdsmdg.tastytoast.TastyToast;

import org.androidannotations.annotations.App;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

/**
 * Created by chezhenzhen on 2017/7/29.
 */

@EBean
public class GearsAuthInterceptor implements ClientHttpRequestInterceptor {
    @App
    DCCXApplication app;
    @Pref
    DCCXSp_ sp;
    @RootContext
    Context context;

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {


        HttpHeaders headers = request.getHeaders();
        headers.add("deviceId", sp.deviceId().get());
        headers.add("token", sp.token().get());
        headers.add("refreshToken", sp.refreshToken().get());
        ClientHttpResponse response = execution.execute(request, body);
        Logger.d("aaaaa  " + response.getStatusCode());
        // TODO: 如果返回state为403,sp清空直接跳转到登录界面,而不进行其他操作
        if (response.getRawStatusCode() == 403 && app.needLogin) {
            sp.token().put("");
            sp.refreshToken().put("");
            app.needLogin = false;
            ((Activity) context).finish();
            Intent intent = new Intent(context, LoginActivity_.class);
            context.startActivity(intent);
        }
        if (response.getHeaders().get("token") != null && !response.getHeaders().get("token").get(0).equals("")) {
            String token = response.getHeaders().get("token").get(0);
            String refreshToken = response.getHeaders().get("refreshToken").get(0);
            refreshToken(token, refreshToken);
        }

        return response;
    }

    // 刷新本地token
    private void refreshToken(String token, String refreshToken) {
        if (token != null && token != "") {
            sp.token().put(token);
            sp.refreshToken().put(refreshToken);
        }
    }
}
